using UnityEngine;
using UnityEngine.UI;
using TMPro;

public class ChatManager : MonoBehaviour
{
    public static ChatManager Instance; // Singleton instance
    public TMP_Text chatText;
    public RectTransform content;
    public ScrollRect scrollRect;

    void Awake()
    {
        if (Instance == null)
        {
            Instance = this;
        }
        else
        {
            Destroy(gameObject);
        }
    }

    public void AddMessage(string msg)
    {
        chatText.text += "\n" + msg;

        // Recalculate layout immediately
        LayoutRebuilder.ForceRebuildLayoutImmediate(content);

        // Force Unity to wait one frame before snapping scroll (UI needs time to update)
        Canvas.ForceUpdateCanvases();
        scrollRect.verticalNormalizedPosition = 0f; // 0 = bottom, 1 = top
    }

    public void ClearChat()
    {
        chatText.text = string.Empty;
        Canvas.ForceUpdateCanvases();
        scrollRect.verticalNormalizedPosition = 0f;
    }
}
